<script setup>
import ip from '@/utils/baseURL.js';
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Picture, Search } from '@element-plus/icons-vue';
import axios from 'axios';
import debounce from 'lodash/debounce';

// 获取当前用户的 session
const session = localStorage.getItem('session');

// API基础URL
const apiBaseUrl = ip + '/inter';

// 上传URL
const uploadUrl = computed(() => `${apiBaseUrl}/upload`);

// 表格数据和加载状态
const honorList = ref([]);
const tableLoading = ref(false);

// 搜索关键词
const searchKeyword = ref('');

// 年份筛选
const selectedYear = ref('');
const availableYears = ref([]);
const allHonors = ref([]); // 存储所有荣誉数据，用于前端筛选

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 对话框控制
const dialogVisible = ref(false);
const isEditing = ref(false);
const submitting = ref(false);

// 表单引用和数据
const honorFormRef = ref(null);
const honorForm = reactive({
  id: null,
  title: '',
  type: '',
  awardDate: '',
  winnerName: '',
  description: '',
  picture: ''
});

// 表单验证规则
const formRules = {
  title: [
    { required: true, message: '请输入荣誉名称', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择荣誉类型', trigger: 'change' }
  ],
  awardDate: [
    { required: true, message: '请选择获奖日期', trigger: 'change' }
  ],
  winnerName: [
    { required: true, message: '请输入获奖人或团队名称', trigger: 'blur' }
  ]
};

// 获取荣誉类型标签样式
const getHonorTypeTag = (type) => {
  const tags = {
    teaching: 'success',
    research: 'primary',
    competition: 'warning',
    advanced: 'danger',
    other: 'info'
  };
  return tags[type] || 'info';
};

// 获取荣誉类型标签文本
const getHonorTypeLabel = (type) => {
  const labels = {
    teaching: '教学成果',
    research: '科研成果',
    competition: '竞赛奖项',
    advanced: '先进集体/个人',
    other: '其他荣誉'
  };
  return labels[type] || '未知类型';
};

// 处理年份变化
const handleYearChange = () => {
  pagination.currentPage = 1;
  loadHonorList();
};

// 从日期中提取年份
const extractYear = (dateString) => {
  if (!dateString) return null;
  return parseInt(dateString.split('-')[0]);
};

// 加载荣誉列表数据
const loadHonorList = async () => {
  tableLoading.value = true;
  try {
    // 构建查询参数
    const params = {
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      // 根据搜索条件构建查询对象
      title: searchKeyword.value || undefined,
      winners: searchKeyword.value || undefined
    };
    
    const response = await axios.get(`${apiBaseUrl}/honor/get`, { params });
    
    if (response.data.code === 200) {
      // 处理数据格式差异
      const records = response.data.data.records || [];
      
      // 存储所有数据以便前端筛选
      allHonors.value = records.map(item => ({
        id: item.id,
        title: item.title,
        type: mapHonorType(item.type),
        awardDate: formatDate(item.time),
        winnerName: item.winners,
        description: item.briInfo,
        picture: item.image,
        year: item.time && Array.isArray(item.time) ? item.time[0] : 
              (typeof item.time === 'string' ? extractYear(item.time) : null)
      }));
      
      // 提取所有年份并排序
      const years = new Set();
      allHonors.value.forEach(honor => {
        if (honor.year) {
          years.add(honor.year);
        }
      });
      availableYears.value = Array.from(years).sort((a, b) => b - a); // 降序排列
      
      // 应用年份筛选
      let filteredHonors = allHonors.value;
      if (selectedYear.value) {
        filteredHonors = filteredHonors.filter(honor => 
          honor.year === selectedYear.value || honor.year === parseInt(selectedYear.value)
        );
      }
      
      honorList.value = filteredHonors;
      pagination.total = filteredHonors.length;
    } else {
      ElMessage.error(response.data.message || '获取荣誉信息失败');
    }
  } catch (error) {
    console.error('加载荣誉信息错误:', error);
    ElMessage.error('网络错误，请稍后重试');
  } finally {
    tableLoading.value = false;
  }
};

// 格式化日期数组为字符串
const formatDate = (dateArray) => {
  if (!dateArray || !Array.isArray(dateArray) || dateArray.length < 3) {
    return '';
  }
  const [year, month, day] = dateArray;
  // 补充前导零
  const formattedMonth = month.toString().padStart(2, '0');
  const formattedDay = day.toString().padStart(2, '0');
  return `${year}-${formattedMonth}-${formattedDay}`;
};

// 映射荣誉类型
const mapHonorType = (type) => {
  const typeMap = {
    '教学成果': 'teaching',
    '科研奖项': 'research',
    '竞赛奖项': 'competition',
    '先进集体/个人': 'advanced'
  };
  return typeMap[type] || 'other';
};

// 搜索防抖
const debounceSearch = debounce(() => {
  pagination.currentPage = 1;
  loadHonorList();
}, 300);

// 处理页面大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size;
  loadHonorList();
};

// 处理页码变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page;
  loadHonorList();
};

// 添加荣誉信息
const handleAddHonor = () => {
  isEditing.value = false;
  resetForm();
  dialogVisible.value = true;
};

// 编辑荣誉信息
const handleEditHonor = (row) => {
  isEditing.value = true;
  resetForm();
  
  // 复制数据到表单
  honorForm.id = row.id;
  honorForm.title = row.title;
  honorForm.type = row.type;
  honorForm.awardDate = row.awardDate;
  honorForm.winnerName = row.winnerName;
  honorForm.description = row.description;
  honorForm.picture = row.picture;
  
  dialogVisible.value = true;
};

// 删除荣誉信息
const handleDeleteHonor = (row) => {
  ElMessageBox.confirm(`确定要删除荣誉"${row.title}"吗？此操作不可恢复！`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 这里替换为实际的删除API
      const response = await axios.delete(`${apiBaseUrl}/honor/${row.id}`,{headers: {
        'Session': `${session}`, // 传递 session
      },
      });
      
      if (response.data.code === 200) {
        ElMessage.success('删除成功');
        loadHonorList();
      } else {
        ElMessage.error(response.data.message || '删除失败');
      }
    } catch (error) {
      console.error('删除荣誉信息错误:', error);
      ElMessage.error('网络错误，请稍后重试');
    }
  }).catch(() => {});
};

// 重置表单
const resetForm = () => {
  if (honorFormRef.value) {
    honorFormRef.value.resetFields();
  }
  honorForm.id = null;
  honorForm.title = '';
  honorForm.type = '';
  honorForm.awardDate = '';
  honorForm.winnerName = '';
  honorForm.description = '';
  honorForm.picture = '';
};

// 提交荣誉表单
const submitHonorForm = () => {
  honorFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true;
      try {
        // 转换成后端期望的格式
        const formData = {
          id: honorForm.id,
          title: honorForm.title,
          type: reverseMapHonorType(honorForm.type),
          time: honorForm.awardDate,
          winners: honorForm.winnerName,
          briInfo: honorForm.description,
          image: honorForm.picture || null
        };
        
        // 使用新的接口URL
        const url = `${apiBaseUrl}/honor/saveOrUpdateInfo`;
          
        const response = await axios.post(url, formData,{headers: {
          'Session': `${session}`, // 传递 session
        },
        });
        
        if (response.data.code === 200) {
          ElMessage.success(isEditing.value ? '更新成功' : '添加成功');
          dialogVisible.value = false;
          loadHonorList();
        } else {
          ElMessage.error(response.data.message || (isEditing.value ? '更新失败' : '添加失败'));
        }
      } catch (error) {
        console.error('提交荣誉信息错误:', error);
        ElMessage.error('网络错误，请稍后重试');
      } finally {
        submitting.value = false;
      }
    }
  });
};

// 将parseDate函数保留但不再使用，以便未来可能需要时仍可用
const parseDate = (dateString) => {
  if (!dateString) return null;
  const [year, month, day] = dateString.split('-').map(num => parseInt(num, 10));
  return [year, month, day];
};

// 反向映射荣誉类型
const reverseMapHonorType = (type) => {
  const reverseTypeMap = {
    'teaching': '教学成果',
    'research': '科研奖项',
    'competition': '竞赛奖项',
    'advanced': '先进集体/个人',
    'other': '其他荣誉'
  };
  return reverseTypeMap[type] || '其他荣誉';
};

// 修改上传头信息的定义
const uploadHeaders = {
  'Session': `${session}`
}

// 图片上传前检查
const beforePictureUpload = (file) => {
  console.log('准备上传文件:', file);
  const isImage = file.type.startsWith('image/');
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error('只能上传图片文件!');
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!');
  }

  // 添加日志查看上传状态
  console.log('文件验证结果:', isImage && isLt2M);
  return isImage && isLt2M;
};

// 图片上传成功处理
const handlePictureSuccess = (response) => {
  console.log('上传响应:', response);
  
  if (response.code === 200) {
    honorForm.picture = response.data;
    ElMessage.success('图片上传成功');
    console.log('荣誉图片上传成功，URL:', response.data);
  } else {
    ElMessage.error(response.message || '图片上传失败');
  }
};

// 图片上传错误处理
const handlePictureError = (error, file) => {
  console.error('图片上传错误:', error);
  console.log('错误相关文件:', file);
  ElMessage.error('图片上传失败，请检查网络连接或联系管理员');
};

// 页面初始化时加载数据
onMounted(() => {
  loadHonorList();
});
</script>

<template>
  <div class="honor-container">
    <div class="page-header">
      <h1>荣誉信息管理</h1>
    </div>

    <!-- 功能按钮区域 -->
    <div class="actions-panel">
      <el-button type="primary" @click="handleAddHonor">添加荣誉信息</el-button>
      <div class="filter-panel">
        <el-select
          v-model="selectedYear"
          placeholder="选择年份"
          clearable
          @change="handleYearChange"
          class="year-select"
        >
          <el-option
            v-for="year in availableYears"
            :key="year"
            :label="year + '年'"
            :value="year"
          />
        </el-select>
        <div class="search-panel">
          <el-input 
            v-model="searchKeyword" 
            placeholder="搜索荣誉名称或获奖人" 
            clearable 
            @clear="loadHonorList" 
            @input="debounceSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
      </div>
    </div>

    <!-- 荣誉信息表格 -->
    <el-table 
      :data="honorList" 
      style="width: 100%" 
      border 
      v-loading="tableLoading"
    >
      <el-table-column label="序号" type="index" width="60" align="center" />
      <el-table-column prop="title" label="荣誉名称" min-width="180" />
      <el-table-column prop="type" label="荣誉类型" width="120">
        <template #default="scope">
          <el-tag :type="getHonorTypeTag(scope.row.type)">
            {{ getHonorTypeLabel(scope.row.type) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="awardDate" label="获奖日期" width="120" sortable />
      <el-table-column prop="winnerName" label="获奖人/团队" min-width="140" />
      <el-table-column label="荣誉图片" width="100">
        <template #default="scope">
          <el-image
            v-if="scope.row.picture"
            :src="scope.row.picture"
            style="width: 60px; height: 60px"
            fit="cover"
            :preview-src-list="[scope.row.picture]"
          />
          <el-icon v-else style="font-size: 24px; color: #909399;"><Picture /></el-icon>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="描述" min-width="220">
        <template #default="scope">
          <div class="description-cell">
            {{ scope.row.description || '暂无描述' }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEditHonor(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDeleteHonor(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑荣誉信息对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditing ? '编辑荣誉信息' : '添加荣誉信息'"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="honorForm" label-width="100px" :rules="formRules" ref="honorFormRef">
        <el-form-item label="荣誉名称" prop="title">
          <el-input v-model="honorForm.title" placeholder="请输入荣誉名称" />
        </el-form-item>
        <el-form-item label="荣誉类型" prop="type">
          <el-select v-model="honorForm.type" placeholder="请选择荣誉类型" style="width: 100%">
            <el-option label="教学成果" value="teaching" />
            <el-option label="科研成果" value="research" />
            <el-option label="竞赛奖项" value="competition" />
            <el-option label="先进集体/个人" value="advanced" />
            <el-option label="其他荣誉" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="获奖日期" prop="awardDate">
          <el-date-picker 
            v-model="honorForm.awardDate" 
            type="date" 
            placeholder="选择获奖日期"
            style="width: 100%"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="获奖人/团队" prop="winnerName">
          <el-input v-model="honorForm.winnerName" placeholder="请输入获奖人或团队名称" />
        </el-form-item>
        <el-form-item label="荣誉描述" prop="description">
          <el-input 
            v-model="honorForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入荣誉的详细描述"
          />
        </el-form-item>
        <el-form-item label="荣誉图片">
          <div class="avatar-controls">
            <el-upload
              class="honor-uploader"
              :action="uploadUrl"
              :headers="uploadHeaders"
              :show-file-list="false"
              :on-success="handlePictureSuccess"
              :before-upload="beforePictureUpload"
              :on-error="handlePictureError"
              name="image"
              accept="image/*"
            >
              <img v-if="honorForm.picture" :src="honorForm.picture" class="honor-image" />
              <el-icon v-else class="honor-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <div class="upload-actions">
              <div class="upload-tip">
                <p>点击上传荣誉证书或相关图片(可选)</p>
                <p class="tip-detail">建议尺寸: 800x600像素，JPG/PNG格式</p>
                <p class="tip-detail">文件大小不超过2MB</p>
              </div>
              <el-button 
                type="warning" 
                size="small" 
                @click="honorForm.picture = ''"
                :disabled="!honorForm.picture"
              >
                移除图片
              </el-button>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitHonorForm" :loading="submitting">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>



<style lang="scss" scoped>
.honor-container {
  padding: 20px;
  
  .page-header {
    margin-bottom: 20px;
    
    h1 {
      font-size: 24px;
      margin: 0;
    }
  }
  
  .actions-panel {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    
    .filter-panel {
      display: flex;
      gap: 10px;
      align-items: center;
      
      .year-select {
        width: 120px;
      }
      
      .search-panel {
        width: 250px;
      }
    }
  }
  
  .description-cell {
    max-width: 250px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .avatar-controls {
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .honor-uploader {
      display: flex;
      justify-content: center;
      
      .honor-image {
        width: 150px;
        height: 150px;
        object-fit: cover;
        border-radius: 4px;
        max-width: 100%;
      }
      
      .honor-uploader-icon {
        width: 150px;
        height: 150px;
        border: 1px dashed #d9d9d9;
        border-radius: 4px;
        font-size: 28px;
        color: #8c939d;
        display: flex;
        justify-content: center;
        align-items: center;
        
        &:hover {
          border-color: #409EFF;
        }
      }
    }
    
    .upload-actions {
      margin-top: 8px;
      width: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      
      .el-button {
        margin-top: 8px;
      }
      
      .upload-tip {
        text-align: center;
        color: #909399;
        font-size: 14px;
        
        .tip-detail {
          font-size: 12px;
          margin-top: 4px;
          color: #C0C4CC;
        }
      }
    }
  }
  
  /* 确保el-image组件中的图片大小 */
  :deep(.el-image) {
    img {
      max-width: 100%;
      max-height: 300px;
      object-fit: contain;
    }
  }
  
  /* 限制图片预览弹窗中的图片大小 */
  :deep(.el-image-viewer__wrapper) {
    .el-image-viewer__img {
      max-width: 80vw;
      max-height: 80vh;
    }
  }
}

:deep(.el-table) {
  margin-bottom: 20px;
}
</style>